package org.catspaw.cherubim.persistence.jpa.spring;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import org.catspaw.cherubim.persistence.DynamicProxyResourceMaster;
import org.catspaw.cherubim.persistence.ResourceCallback;
import org.catspaw.cherubim.persistence.jpa.EntityManagerMaster;

public class SpringJpaEntityManagerMaster extends JpaDaoSupport implements EntityManagerMaster {

	private DynamicProxyResourceMaster<EntityManager>	delegate;

	public SpringJpaEntityManagerMaster() {
		delegate = new DynamicProxyResourceMaster<EntityManager>(EntityManager.class) {

			public <T> T execute(ResourceCallback<EntityManager, T> callback) {
				return SpringJpaEntityManagerMaster.this.execute(callback);
			}
		};
	}

	public <T> T execute(final ResourceCallback<EntityManager, T> callback) {
		return getJpaTemplate().execute(new JpaCallback<T>() {

			public T doInJpa(EntityManager em) throws PersistenceException {
				return callback.doInResource(em);
			}
		});
	}

	public EntityManager getResource() {
		return delegate.getResource();
	}
}
